var remote = {
	getPost: function(url, callback) {
		// http://code.google.com/apis/blogger/docs/2.0/developers_guide_protocol.html
		// get specific post from blog
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function(data) {
			if (xhr.readyState == 4) {
				callback((xhr.status == 200) ? xhr.responseText : null);
			}
		}
		console.log('loading ' + url);
		xhr.open('GET', url, true);
		xhr.send();
	},
	getBlog: function(url, callback) {
		// get the list of posts at the given blog
		url = ti.data.get('feed');
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function(data) {
			if (xhr.readyState == 4) {
				var r = new responseObject(url);
				if (xhr.status == 200 && xhr.responseXML) {
					callback(r.parseFeed(xhr.responseXML));
				} else {
					callback(r);
				}
			}
		}
		console.log('loading ' + url);
		xhr.open('GET', url, true);
		xhr.send();
	}
};

var _title = ti.data.get('title');
var _url = ti.data.get('blog');
var _color = ti.data.get('color');

ti.menu.newItem('Insert ' + _title + ' Post', ['editable'], function(info, tab) {
	chrome.tabs.sendRequest(tab.id, {
		"title": _title,
		"url": _url,
		"color": _color
	});
});

chrome.extension.onRequest.addListener(function(request, sender, callback) {
	remote[request.action](request.id, callback);
});

function responseObject(url, error) {
	var _this = this;
	this.posts = [];
	this.url = url;
	this.error = error;
	this.complete = false;
	
	this.parseFeed = function(xml) {
		var entries = xml.getElementsByTagName('entry');
		for (var i = 0; i < entries.length; i++) {
			_this.posts.push(new postObject(entries[i]));
		}
		_this.complete = true;
		return _this;
	}
}

function postObject(entry) {
	this.title = entry.getElementsByTagName('title')[0].textContent;
	this.url = getPostUrl(entry);
	
	function getPostUrl(entry) {
		var links = entry.getElementsByTagName('link');
		for (var i = 0; i < links.length; i++) {
			if (links[i].getAttribute('rel') == 'alternate') {
				return links[i].getAttribute('href');
			}
		}
		return null;
	}
}